import axios from 'axios'

//前端拦截器-axios
//以下来源axios github 请求拦截器 别忘记在main.js内引入

// 请求发出之前的拦截 Add a request interceptor
axios.interceptors.request.use(function (config) {
    // Do something before request is sent
    // console.log("前端-请求发出之前的拦截", config)
    //前端每次发请求之前把本地localStorage内的token取出来传给后端 第一次登陆时候会是空
    const token = localStorage.getItem("token")
    config.headers.Authorization = `Bearer ${token}`

    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });

// 请求得到响应的拦截 Add a response interceptor
axios.interceptors.response.use(function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    // console.log("前端-请求得到响应的axios拦截器工作了吗", response.headers)
    //登陆成功后 前端提取 拦截到的后端返回的token/ActionType 存起来
    //然后去后端统一获取token进行验证工作即可；
    const {authorization } = response.headers
    authorization && localStorage.setItem("token", authorization)

    return response;
  }, function (error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    const {status} = error.response
    if(status === 401){
      localStorage.removeItem("token")
      //视频上讲的是'#/login'
      window.location.href = "/login"
    }
    return Promise.reject(error);
  });